package com.github.prontera.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.github.prontera.client.BaseRequestListener;
import com.github.prontera.client.DownloadListener;
import com.github.prontera.client.OperationCanceledException;
import com.github.prontera.client.RestRequest;
import com.github.prontera.domain.Client;
import com.github.prontera.domain.IssueAnswer;
import com.github.prontera.domain.enums.GenderEnum;
import com.github.prontera.persistence.ClientMapper;
import com.github.prontera.util.DateTimeUtil;
import com.github.prontera.util.URLUtils;

/**
 * 客户端
 */
@Component
public class DownloadComponent {
	
	@Autowired
	private ClientMapper clientMapper;
	@Autowired
	private IssueAnswerService issueAnswerService;
	
	private static String imageIp = "http://image.yuejiulai.com";
	private static String videoIp = "http://video.yuejiulai.com";
//	private static String imageIp = "http://127.0.0.1:8081/media";
//	private static String videoIp = "http://127.0.0.1:8081/media";

	private void download(Long id,String uid, IssueAnswer issueAnswer) {
		String datePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy/MM/dd");
		String httpDatePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy/MM/dd");

		if (!new File("/data/media/" + id +"/" + datePath +  "/").exists()) {
			new File("/data/media/" + id + "/" + datePath + "/").mkdirs();
		}

		String[] imagePngUrls = issueAnswer.getImage().split("[//]");
		String imageFilename = imagePngUrls[imagePngUrls.length - 1];
		String imagehttpDatePath = imageIp + "/" + id + "/" + httpDatePath + "/" + imageFilename;

		String[] videoPngUrls = issueAnswer.getVideo().split("[//]");
		String videoFilename = videoPngUrls[videoPngUrls.length - 1];
		String videohttpDatePath = videoIp + "/" + id + "/" + httpDatePath + "/" + videoFilename;

		String[] headImagePngUrls = issueAnswer.getHeadImage().split("[//]");
		String headImageFilename = headImagePngUrls[headImagePngUrls.length - 1];
		String headImagehttpDatePath = imageIp + "/" + id + "/" + httpDatePath + "/" + headImageFilename;
		
		RestRequest request = new RestRequest(issueAnswer.getImage());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("/data/media/" +id  + "/" +  datePath+ "/" + imageFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});

		request = new RestRequest(issueAnswer.getVideo());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("/data/media/" +id  + "/" + datePath + "/" + videoFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});
		
		request = new RestRequest(issueAnswer.getHeadImage());
		request.addHeader("User-Agent",
				"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.download("/data/media/" + id + "/" + datePath + "/" + headImageFilename, new DownloadListener() {

			public void onError(Exception ex) {

			}

			public void onProgress(float progress, float total) throws OperationCanceledException {

			}

			@Override
			public void onComplete(Object response) {

			}
		});
		
		Client client = new Client();
		client.setId(id);
		client.setHeadImage(headImagehttpDatePath);
		clientMapper.update(client);
		
		issueAnswer.setVideo(videohttpDatePath);
		issueAnswer.setImage(imagehttpDatePath);
		issueAnswerService.insert(issueAnswer);
		
	}
	
	public void getUserInfo(String uid)  {
		Map<String, String> params = new HashMap<String, String>();
		
		String uri = URLUtils.append("http://120.25.135.13//api/user/"+uid, params);
		RestRequest request = new RestRequest(uri);
		request.addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		Object objectNode = request.get();
		System.out.println(objectNode);
		
		
		String uri2 = URLUtils.append("http://120.25.135.13/api/user/"+uid+"/videos2?v=2.7.2&dev=android&dev_version=8.0.0&dev_name=DUK-AL20&uuid=ea8fceffc05b242f", params);
		RestRequest request2  = new RestRequest(uri2);
		request2 .addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request2 .addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		
		String conten=(String)request2.get();
		
		startdDwnVedio(uid,conten);
	}
	
	private void startDownAvatar(Long clientId,String uid) {
		Map<String, String> params = new HashMap<String, String>();
		String uri = URLUtils.append("http://120.25.135.13//api/user/"+uid, params);
		RestRequest request = new RestRequest(uri);
		request.addHeader("User-Agent","Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
		request.addHeader("X-Api-Token", "42E4AF30571346CCA063AA5C1A260C00");
		request.get(new BaseRequestListener() {
			public void onError(Exception ex) {

			}

			public void onComplete(Object response) {
				String objectNode = (String) response;
				System.out.println(objectNode);
				JSONObject jsonObject = new JSONObject(objectNode);
				JSONObject jsonDataObj = jsonObject.getJSONObject("data");
				
				String avatar = jsonDataObj.getString("avatar");
				Integer gender = jsonDataObj.getInt("gender");
				
				JSONArray jsonArray =jsonDataObj.optJSONArray("photos");
				System.out.println(jsonArray.length());
				List<String> avatars=new ArrayList<String>();
				for (int i = 0; i < jsonArray.length(); i++) {
					JSONObject skObj = jsonArray.getJSONObject(i);
					if (skObj != null) {
						String url = skObj.getString("url");
						System.out.println("-----------------------1-----------avatar["+url+"]");
						String datePath = DateTimeUtil.formatDateTimetoString(DateTimeUtil.getSystemDate(), "yyyy/MM/dd");

						if (!new File("/data/media/" + clientId + "/" + datePath + "/").exists()) {
							new File("/data/media/" +clientId  + "/" + datePath + "/").mkdirs();
						}

						String[] imagePngUrls = url.split("[//]");
						String imageFilename = imagePngUrls[imagePngUrls.length - 1];
						String imagehttpDatePath = imageIp + "/" + clientId + "/" + datePath + "/" + imageFilename;

						System.err.println("/data/media/" + clientId + "/" + datePath + "/" + imageFilename);
						
						imagehttpDatePath=imagehttpDatePath.replace("/", "/");
						
						avatars.add(imagehttpDatePath);
						
						RestRequest request = new RestRequest(url);
						request.addHeader("User-Agent",
								"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
						request.download("/data/media/" + clientId + "/" + datePath + "/" + imageFilename, new DownloadListener() {

							public void onError(Exception ex) {

							}

							public void onProgress(float progress, float total) throws OperationCanceledException {

							}

							@Override
							public void onComplete(Object response) {
								
							}
						});
						
						
						String[] avatarPngUrls = url.split("[//]");
						String avatarFilename = avatarPngUrls[avatarPngUrls.length - 1];
						String avatarhttpDatePath = imageIp + "/" + clientId + "/" + datePath + "/" + avatarFilename;
						System.err.println("/data/media/" + clientId + "/" + datePath + "/" + avatarFilename);
						avatar=avatarhttpDatePath=avatarhttpDatePath.replace("/", "/");
						request = new RestRequest(url);
						request.addHeader("User-Agent",
								"Mozilla/5.0 (Linux; Android 7.0; SM-G935P Build/NRD90M) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.92 Mobile Safari/537.36");
						request.download("/data/media/" + clientId + "/" + datePath + "/" + avatarFilename, new DownloadListener() {

							public void onError(Exception ex) {

							}

							public void onProgress(float progress, float total) throws OperationCanceledException {

							}

							@Override
							public void onComplete(Object response) {
								
							}
						});
						
					}
				}
				
				String pString=StringUtils.join(avatars,",");
				Client client = new Client();
				client.setId(clientId);
				client.setHeadImage(avatar);
				if(gender.intValue()==2){
					client.setGender(GenderEnum.FEMALE);
				}else {
					client.setGender(GenderEnum.MALE);
				}
				client.setPhotos(pString);
				try {
					clientMapper.update(client);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	 
	private void startdDwnVedio(String uid,String objectNode) {
		
		Client client = clientMapper.find(new Client() {
			private static final long serialVersionUID = 1L;
			{
				setUid(uid);
			}
		}).get(0);
		
		System.out.println(objectNode);
		JSONObject jsonObject = new JSONObject(objectNode);
		JSONArray jsonArray = jsonObject.optJSONArray("data");
		System.out.println(jsonArray.length());
		if(jsonArray!=null&&jsonArray.length()>0){
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObj = jsonArray.getJSONObject(i);
				JSONObject skObj = jsonObj.optJSONObject("sk");
				JSONObject userObj = skObj.getJSONObject("user");
				

				JSONObject videoObj = skObj.getJSONObject("video");
				IssueAnswer findIssueAnswer = new IssueAnswer();
				findIssueAnswer.setVideo(videoObj.getString("video_url"));
				if (issueAnswerService.count(findIssueAnswer) > 0) {
					continue;
				}
				IssueAnswer issueAnswer = new IssueAnswer();
				issueAnswer.setType(1);
				issueAnswer.setHeadImage(userObj.getString("avatar"));
				issueAnswer.setClientId(client.getId());
				issueAnswer.setImage(videoObj.optString("cover_url"));
				issueAnswer.setIssureClientId(client.getId());
				issueAnswer.setVideo(videoObj.getString("video_url"));

				download(client.getId(),uid, issueAnswer);
			}
		}
		
		startDownAvatar(client.getId(), uid);
	}

}
